<?php

namespace App\Middleware;

use App\Exception\XZXValidationException;

use Hyperf\Contract\TranslatorInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Class TranslatorMiddleware
 * 根据请求头的 locale 字段, 进行 translator 语言设定
 */
class TranslatorMiddleware implements MiddlewareInterface {

    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     * @throws XZXValidationException
     * @throws \Exception
     */
    public function process (ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {

        $whiteList = [
            'en',
            'zh_CN',
        ];

        $locale = $request->getHeaderLine('locale');

        if (in_array($locale, $whiteList)) {
            $this->translator->setLocale($locale);
        }
        else {
            $this->translator->setLocale('en');
        }

        return $handler->handle($request);
    }


}
